package com.hefei.garden.config.netty.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author: yxchen6
 * @date: 2022/7/24 14:52
 * @description:
 */
@Component
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    NettyServerHandler nettyServerHandler;
    @Autowired
    NettyServerLogHandler nettyServerLogHandler;

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        // 以("\n")为结尾分割的解码器，传输的最大值为8K
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        // 字符串编码和解码
        pipeline.addLast("encoder", new StringEncoder(StandardCharsets.UTF_8));
        pipeline.addLast("decoder", new StringDecoder(StandardCharsets.UTF_8));
        // 业务逻辑Handler
        pipeline.addLast("businessHandler", nettyServerHandler);
        // 日志记录
        pipeline.addLast("logHandler", nettyServerLogHandler);
    }
}



